package com.sch.wanandroid.ui.main

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sch.wanandroid.constants.Constants
import com.sch.wanandroid.entity.UserCoinInfo
import com.sch.wanandroid.network.NetWorkManager
import com.sch.wanandroid.util.AppManager
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.lang.Exception

/**
 * Created by Sch.
 * Date: 2020/12/22
 * description:
 */
class MainViewModel : ViewModel() {
    private val _userInfo = MutableLiveData<UserCoinInfo>().apply {
        value = UserCoinInfo("--", "--", "--", "--", "请先登录")
    }
    val userInfo: LiveData<UserCoinInfo> = _userInfo

    private val _errorMsg = MutableLiveData<String?>()
    val errorMsg: LiveData<String?> = _errorMsg

    init {
        if (AppManager.isLogin()) {
            MMKV.defaultMMKV().decodeParcelable(Constants.USERCOININFO, UserCoinInfo::class.java)
                ?.let {
                    _userInfo.value = it
                }
            getUserCoinInfo()
        }
    }

    fun getUserCoinInfo() {
        viewModelScope.launch {
            try {
                val result = NetWorkManager.apiService.getUserInfo()
                if (result.errorCode != 0) {
                    _errorMsg.value = result.errorMsg
                } else {
                    _userInfo.value = result.data
                }
                MMKV.defaultMMKV().encode(Constants.USERCOININFO, userInfo.value)
            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }

    fun clearUserInfo() {
        _userInfo.value = UserCoinInfo("--", "--", "--", "--", "请先登录")
    }

}